import { Button } from '@/components/ui/button';
import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { Input } from '@/components/ui/input';
import useEditorStore from '@/store/use-editor-store';
import { Link2Icon } from 'lucide-react';
import { useState } from 'react';

const LinkButton = () => {
  const editor = useEditorStore((state) => state.editor);

  const [linkURL, setLinkURL] = useState('');

  const onChange = (href: string) => {
    editor?.chain().focus().extendMarkRange('link').setLink({ href }).run();
    setLinkURL('');
  };

  return (
    <DropdownMenu
      onOpenChange={(open) => {
        if (open) {
          setLinkURL(editor?.getAttributes('link').href || '');
        }
      }}
    >
      <DropdownMenuTrigger asChild>
        <Button
          variant="ghost"
          className="h-7 w-auto shrink-0 flex flex-col items-center justify-center rounded-sm hover:bg-neutral-200/80 px-1.5 overflow-hidden text-sm"
        >
          <Link2Icon className="size-4" />
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent className="p-2.5 flex items-center gap-x-2">
        <Input
          placeholder="https://example.com"
          value={linkURL}
          onChange={(e) => {
            setLinkURL(e.target.value);
          }}
        />
        <Button onClick={() => onChange(linkURL)}>Apply</Button>
      </DropdownMenuContent>
    </DropdownMenu>
  );
};

export default LinkButton;
